package com.my.socket.bio.v10;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by ZhongGang
 * at 2018/7/4 15:23
 */
public class Server implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(Server.class);

    private Random random = new Random();
    private ServerSocket serverSocket;
    private ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);

    public Server(String host, int port) throws Exception {
        this.serverSocket = new ServerSocket();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(host, port);
        this.serverSocket.bind(inetSocketAddress);
    }

    @Override
    public void run() {
        try {
            while (true) {
                try {
                    Socket socket = this.serverSocket.accept();
                    LOGGER.info("incoming socket: {}", socket);
                    executorService.submit(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                InputStream inputStream = socket.getInputStream();
                                String request = IOUtils.toString(inputStream, "UTF-8");
                                LOGGER.info("read: {}", request);
                                socket.shutdownInput();

                                //模拟业务操作
                                Thread.sleep(random.nextInt(1000));

                                OutputStream outputStream = socket.getOutputStream();
                                String response = request.toUpperCase();
                                IOUtils.write(response, outputStream, "UTF-8");
                                socket.shutdownOutput();
                                LOGGER.info("write: {}", response);
                            } catch (Exception e) {
                                LOGGER.error("exception caught, the error is {}", e.getMessage());
                            } finally {
                                try {
                                    socket.close();
                                } catch (IOException e) {
                                    LOGGER.error("exception caught, the error is {}", e.getMessage());
                                }
                            }
                        }
                    });
                } catch (Exception e) {
                    LOGGER.error("exception caught, the error is {}", e.getMessage());
                }

            }
        } catch (Exception e) {
            LOGGER.error("exception caught, the error is {}", e.getMessage());
        }
    }

    public static void main(String[] args) throws Exception {
        Server server = new Server("127.0.0.1", 9999);
        new Thread(server).start();
    }
}
